﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using VswService_V7.Utility;

namespace VswService_V7.DataBase.Tables.L3INTERFACE
{
    public class L3INTF_STRIP_INFO
    {
        public L3INTF_STRIP_INFO()
        {
        }

        #region public property
        public static readonly string tableName = "L3INTF_STRIP_INFO";
        public static readonly string fd_eventNo = "EVENT_NO";
        public static readonly string fd_stripNo = "STRIP_NO";
        public static readonly string fd_batchNo = "BATCH_NO";
        public static readonly string fd_taskNo = "TASK_NO";
        public static readonly string fd_isSpy = "IS_SPY";
        public static readonly string fd_isEx = "IS_EX";
        public static readonly string fd_stripDurabilityClass = "STRIP_DURABILITY_CLASS";
        public static readonly string fd_stripSteelGrade = "STRIP_STEEL_GRADE";
        public static readonly string fd_stripHeat = "STRIP_HEAT";
        public static readonly string fd_stripThk = "STRIP_THK";
        public static readonly string fd_stripWidth = "STRIP_WIDTH";
        public static readonly string fd_stripWeight = "STRIP_WEIGHT";
        public static readonly string fd_burrDirection = "BURR_DIRECTION";
        public static readonly string fd_status = "STATUS";
        public static readonly string fd_updateTime = "UPDATE_TIME";
        #endregion

        /// <summary>
        /// L3 adds strips to one task on L2.
        /// </summary>
        /// <param name="event_id"></param>
        /// <returns></returns>
        public static void AddStripstoTask(string event_id)
        {
            try
            {
                string sqlStrip = string.Format("select * from {0} where {1}={2}", tableName, fd_eventNo, event_id);

                DataTable stripTable = OracleHelper.Exct_QueryTable(sqlStrip);

                if (stripTable != null && stripTable.Rows.Count > 0)
                {
                    //check if strip parameter is vaild
                    string reslut = CheckTaskInfoDataVaild(stripTable);

                    if (!string.IsNullOrEmpty(reslut))
                    {
                        LogHelper.WriteLog("L3INTF_STRIP_INFO.ExecuteGeneralTask parameter invalid");
                        string l3infcEventsql = string.Format("update {0} set {1}='{2}',{3}='{4}' where {5}={6}",
                                L3INTF_EVENT.tableName, L3INTF_EVENT.fd_eventStatus, "-1", L3INTF_EVENT.fd_errorInfo, reslut,
                                L3INTF_EVENT.fd_eventNo, event_id);
                        OracleHelper.Exct_NonQuery(l3infcEventsql);
                        return;
                    }


                    //check if task_no is not unique
                    for (int i = 0; i < stripTable.Rows.Count; i++)
                    {
                        if (stripTable.Rows[0][fd_taskNo].ToString() != stripTable.Rows[i][fd_taskNo].ToString())
                        {
                            LogHelper.WriteLog("L3INTF_STRIP_INFO.AddStripstoTask :Too many Task_NO");
                            string l3infcEventsql = string.Format("update {0} set {1}='{2}',{3}='{4}' where {5}={6}",
                                    L3INTF_EVENT.tableName, L3INTF_EVENT.fd_eventStatus, "-1", L3INTF_EVENT.fd_errorInfo, "not unique TASK_NO in one event",
                                    L3INTF_EVENT.fd_eventNo, stripTable.Rows[0][fd_eventNo].ToString());
                            OracleHelper.Exct_NonQuery(l3infcEventsql);
                            return;
                        }
                    }
                    //check if task_no exist
                    string sqlTask = string.Format("select * from {0} where {1}='{2}'", TASK_INFO.tableName, TASK_INFO.fd_taskNo, stripTable.Rows[0][fd_taskNo].ToString());
                    DataTable taskTable = OracleHelper.Exct_QueryTable(sqlTask);
                    if (taskTable == null || taskTable.Rows.Count == 0)
                    {
                        LogHelper.WriteLog("L3INTF_STRIP_INFO.AddStripstoTask :no Task_NO");
                        string l3infcEventsql = string.Format("update {0} set {1}='{2}',{3}='{4}' where {5}={6}",
                                L3INTF_EVENT.tableName, L3INTF_EVENT.fd_eventStatus, "-1", L3INTF_EVENT.fd_errorInfo, "TASK_NO is not exist",
                                L3INTF_EVENT.fd_eventNo, stripTable.Rows[0][fd_eventNo].ToString());
                        OracleHelper.Exct_NonQuery(l3infcEventsql);
                        return;
                    }
                    ExecuteAddStripstoTask(stripTable);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("L3INTF_STRIP_INFO.AddStripstoTask", ex);
                string l3infcEventsql = string.Format("update {0} set {1}='{2}',{3}='{4}' where {5}={6}",
                        L3INTF_EVENT.tableName, L3INTF_EVENT.fd_eventStatus, "-1", L3INTF_EVENT.fd_errorInfo, "Insert Strip Information failed",
                        L3INTF_EVENT.fd_eventNo, event_id);
                OracleHelper.Exct_NonQuery(l3infcEventsql);
                throw (ex);
            }
        }
        private static void ExecuteAddStripstoTask(DataTable stripTable)
        {
            try
            {
                List<string> sqlList = new List<string>();

                for (int i = 0; i < stripTable.Rows.Count; i++)
                {
                    string sqlSTRIP = string.Format("insert into {0} values({1},'{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}')",
                    STRIP_INFO.tableName, stripTable.Rows[i][fd_eventNo].ToString(), stripTable.Rows[i][fd_stripNo].ToString(), stripTable.Rows[i][fd_batchNo].ToString(), "0", stripTable.Rows[i][fd_taskNo].ToString(),
                    stripTable.Rows[i][fd_isSpy].ToString(), stripTable.Rows[i][fd_isEx].ToString(), stripTable.Rows[i][fd_stripDurabilityClass].ToString(), stripTable.Rows[i][fd_stripSteelGrade].ToString(),
                    stripTable.Rows[i][fd_stripHeat].ToString(), stripTable.Rows[i][fd_stripThk].ToString(), stripTable.Rows[i][fd_stripWidth].ToString(), stripTable.Rows[i][fd_stripWeight].ToString(),
                    stripTable.Rows[i][fd_burrDirection].ToString(), stripTable.Rows[i][fd_status].ToString(), stripTable.Rows[i][fd_updateTime].ToString());                
                    sqlList.Add(sqlSTRIP);                    
                }

                string l3infcEventsql = string.Format("update {0} set {1}={2} where {3}={4}", L3INTF_EVENT.tableName, L3INTF_EVENT.fd_eventStatus, "2", L3INTF_EVENT.fd_eventNo, stripTable.Rows[0][fd_eventNo].ToString());
                sqlList.Add(l3infcEventsql);
                OracleHelper.ExecuteSqlTran(sqlList);

                LogHelper.WriteLog("L3INTF_STRIP_INFO.ExecuteAddStripstoTask Success!");
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("L3INTF_STRIP_INFO.ExecuteAddStripstoTask", ex);
                string l3infcEventsql = string.Format("update {0} set {1}='{2}',{3}='{4}' where {5}={6}",
                        L3INTF_EVENT.tableName, L3INTF_EVENT.fd_eventStatus, "-1", L3INTF_EVENT.fd_errorInfo, "Insert Strip Information failed",
                        L3INTF_EVENT.fd_eventNo, stripTable.Rows[0][fd_eventNo].ToString());
                OracleHelper.Exct_NonQuery(l3infcEventsql);

                throw ex;
            }
        }

        /// <summary>
        /// L3 updates a strip information.
        /// </summary>
        /// <param name="event_id"></param>
        /// <returns></returns>
        public static void UpdateStrip(string event_id)
        {
            try
            {
                string sqlStrip = string.Format("select * from {0} where {1}={2}", tableName, fd_eventNo, event_id);
                DataTable stripTable = OracleHelper.Exct_QueryTable(sqlStrip);
                if (stripTable != null && stripTable.Rows.Count == 1)
                {
                    ExecuteUpdateStrip(stripTable);
                }
                else
                {
                    //如果一个时间增加了多个
                    string l3infcEventsql = string.Format("update {0} set {1}='{2}',{3}='{4}' where {5}={6}",
                        L3INTF_EVENT.tableName, L3INTF_EVENT.fd_eventStatus, "-1", L3INTF_EVENT.fd_errorInfo, "not unique strip_no",
                        L3INTF_EVENT.fd_eventNo, event_id);
                    OracleHelper.Exct_NonQuery(l3infcEventsql);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("L3INTF_STRIP_INFO.UpdateStrip", ex);
                throw (ex);
            }
        }
        private static void ExecuteUpdateStrip(DataTable stripTable)
        {
            try
            {
                string sqlSTRIP = string.Format("UPDATE {0} SET {1}={2}, {3}='{4}', {5}='{6}',{7}='{8}',{9}='{10}',{11}='{12}',{13}='{14}',{15}='{16}',{17}='{18}',{19}='{20}'" +
                            ",{21}='{22}',{23}='{24}',{25}='{26}',{27}='{28}', {29}='{30}' where {31}='{32}'",
                               STRIP_INFO.tableName, fd_eventNo, stripTable.Rows[0][fd_eventNo].ToString(), STRIP_INFO.fd_batchNoE, stripTable.Rows[0][fd_batchNo].ToString(), STRIP_INFO.fd_batchNoO, "0",
                               fd_taskNo, stripTable.Rows[0][fd_taskNo].ToString(), fd_isSpy, stripTable.Rows[0][fd_isSpy].ToString(), fd_isEx, stripTable.Rows[0][fd_isEx].ToString(), fd_stripDurabilityClass, stripTable.Rows[0][fd_stripDurabilityClass].ToString(), fd_stripSteelGrade, stripTable.Rows[0][fd_stripSteelGrade].ToString(),
                               fd_stripHeat, stripTable.Rows[0][fd_stripHeat].ToString(), fd_stripThk, stripTable.Rows[0][fd_stripThk].ToString(), fd_stripWidth, stripTable.Rows[0][fd_stripWidth].ToString(), fd_stripWeight, stripTable.Rows[0][fd_stripWeight].ToString(), fd_burrDirection, stripTable.Rows[0][fd_burrDirection].ToString(),
                               fd_status, stripTable.Rows[0][fd_status].ToString(), fd_updateTime, stripTable.Rows[0][fd_updateTime].ToString(), fd_stripNo, stripTable.Rows[0][fd_stripNo].ToString());
                string l3infcEventsql = string.Format("update {0} set {1}={2} where {3}={4}", L3INTF_EVENT.tableName, L3INTF_EVENT.fd_eventStatus, "2", L3INTF_EVENT.fd_eventNo, stripTable.Rows[0][fd_eventNo].ToString());
                List<string> sqlList = new List<string>();

                //close temporary 2022-04-07 for L3 3011 bug
                //sqlList.Add(sqlSTRIP);

                sqlList.Add(l3infcEventsql);
                OracleHelper.ExecuteSqlTran(sqlList);
                LogHelper.WriteLog("L3INTF_STRIP_INFO.ExecuteUpdateStrip Success!");
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("L3INTF_STRIP_INFO.ExecuteUpdateStrip", ex);
                throw ex;
            }
        }

        public static string CheckTaskInfoDataVaild(DataTable stripTable)
        {
            for (int i = 0; i < stripTable.Rows.Count; i++)
            {
                //if (!int.TryParse(stripTable.Rows[i][STRIP_INFO.fd_isSpy].ToString(), out int spy))
                //{
                //    return "strip " + stripTable.Rows[i][STRIP_INFO.fd_stripNo].ToString() + " IS_SPY invalid";
                //}

                //if (!int.TryParse(stripTable.Rows[i][STRIP_INFO.fd_isEx].ToString(), out int ex))
                //{
                //    return "strip " + stripTable.Rows[i][STRIP_INFO.fd_stripNo].ToString() + " IS_EX invalid";
                //}

                if (!double.TryParse(stripTable.Rows[i][STRIP_INFO.fd_stripThk].ToString(), out double thk))
                {
                    return "strip " + stripTable.Rows[i][STRIP_INFO.fd_stripNo].ToString() + " thinckness invalid";
                }

                if (!double.TryParse(stripTable.Rows[i][STRIP_INFO.fd_stripWidth].ToString(), out double width))
                {
                    return "strip " + stripTable.Rows[i][STRIP_INFO.fd_stripNo].ToString() + " width invalid";
                }

                if (!double.TryParse(stripTable.Rows[i][STRIP_INFO.fd_stripWeight].ToString(), out double weight))
                {
                    return "strip " + stripTable.Rows[i][STRIP_INFO.fd_stripNo].ToString() + " weight invalid";
                }

                //if (!int.TryParse(stripTable.Rows[i][STRIP_INFO.fd_burrDirection].ToString(), out int burr))
                //{
                //    return "strip " + stripTable.Rows[i][STRIP_INFO.fd_stripNo].ToString() + " BURR_DIRECTION invalid";
                //}
            }
            return "";
        }
    }
}
